#!/bin/bash

# Author: Tiany
# Linux 深度巡检工具箱
# 提供全面的系统安全检查、性能监控、配置合规性检查等深度巡检功能
# 适用于运维工程师日常深度巡检需求

# 移除 set -e 避免正常的命令失败导致脚本退出
# set -e

# 全局配置
SCRIPT_VERSION="2.0"
REPORT_DIR="/tmp/system_inspection_$(date +%Y%m%d_%H%M%S)"
LOG_FILE="$REPORT_DIR/inspection.log"
HTML_REPORT="$REPORT_DIR/inspection_report.html"

# 阈值配置 - 可根据实际需求调整
CPU_THRESHOLD=80
MEM_THRESHOLD=80
DISK_THRESHOLD=80
LOAD_THRESHOLD=2.0
FAILED_LOGIN_THRESHOLD=10

# 使用 tput 设置颜色，增强兼容性
RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
YELLOW=$(tput setaf 3)
BLUE=$(tput setaf 4)
NC=$(tput sgr0)

cols=$(tput cols)

print_header() {
    printf "${BLUE}%-${cols}s\n" "================================"
    printf "${BLUE}%-${cols}s\n" "    Linux 系统工具箱"
    printf "${BLUE}%-${cols}s\n" "================================"
}

print_section() {
    echo -e "\n${GREEN}=== $1 ===${NC}"
}

print_separator() {
    printf "${BLUE}%-${cols}s\n" "--------------------------------"
}

# 创建报告目录和日志文件
init_report() {
    mkdir -p "$REPORT_DIR"
    echo "=== 系统深度巡检开始 ===" > "$LOG_FILE"
    echo "时间: $(date)" >> "$LOG_FILE"
    echo "主机: $(hostname)" >> "$LOG_FILE"
    echo "======================" >> "$LOG_FILE"
}

# 日志记录函数
log_info() {
    echo "[INFO] $(date '+%Y-%m-%d %H:%M:%S') $1" >> "$LOG_FILE"
}

log_warning() {
    echo "[WARNING] $(date '+%Y-%m-%d %H:%M:%S') $1" >> "$LOG_FILE"
    echo -e "${YELLOW}⚠️  $1${NC}"
}

log_critical() {
    echo "[CRITICAL] $(date '+%Y-%m-%d %H:%M:%S') $1" >> "$LOG_FILE"
    echo -e "${RED}🚨 $1${NC}"
}

log_success() {
    echo "[SUCCESS] $(date '+%Y-%m-%d %H:%M:%S') $1" >> "$LOG_FILE"
    echo -e "${GREEN}✅ $1${NC}"
}

# 检查命令是否存在
check_command() {
    command -v "$1" >/dev/null 2>&1
}

show_basic_info() {
    print_section "基础系统信息"
    
    echo -e "${YELLOW}主机名:${NC} $(hostname)"
    echo -e "${YELLOW}当前用户:${NC} $(whoami)"
    echo -e "${YELLOW}当前时间:${NC} $(date)"
    echo -e "${YELLOW}系统运行时间:${NC} $(uptime -p 2>/dev/null || uptime)"
    
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        echo -e "${YELLOW}操作系统:${NC} $PRETTY_NAME"
        echo -e "${YELLOW}版本ID:${NC} $VERSION_ID"
    else
        echo -e "${YELLOW}操作系统:${NC} $(uname -s) $(uname -r)"
    fi
    
    echo -e "${YELLOW}内核版本:${NC} $(uname -r)"
    echo -e "${YELLOW}架构:${NC} $(uname -m)"
}

show_hardware_info() {
    print_section "硬件信息"
    
    # CPU信息
    if [ -f /proc/cpuinfo ]; then
        cpu_model=$(grep "model name" /proc/cpuinfo | head -1 | cut -d: -f2 | sed 's/^ *//')
        cpu_cores=$(grep -c "^processor" /proc/cpuinfo)
        echo -e "${YELLOW}CPU:${NC} $cpu_model"
        echo -e "${YELLOW}CPU核心数:${NC} $cpu_cores"
    fi
    
    # 内存信息
    if [ -f /proc/meminfo ]; then
        mem_total=$(grep "MemTotal" /proc/meminfo | awk '{printf "%.1f GB", $2/1024/1024}')
        mem_free=$(grep "MemAvailable" /proc/meminfo | awk '{printf "%.1f GB", $2/1024/1024}')
        mem_used=$(grep -E "MemTotal|MemAvailable" /proc/meminfo | awk 'NR==1{total=$2} NR==2{avail=$2} END{printf "%.1f GB", (total-avail)/1024/1024}')
        echo -e "${YELLOW}内存总量:${NC} $mem_total"
        echo -e "${YELLOW}已使用内存:${NC} $mem_used"
        echo -e "${YELLOW}可用内存:${NC} $mem_free"
    fi
}

show_disk_info() {
    print_section "磁盘使用情况"
    
    echo -e "${YELLOW}文件系统使用情况:${NC}"
    df -h | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{
        printf "%-20s %8s %8s %8s %5s %s\n", $1, $2, $3, $4, $5, $6
    }' | while read line; do
        usage=$(echo $line | awk '{print $5}' | sed 's/%//')
        if [ "$usage" -gt 80 ]; then
            echo -e "${RED}$line${NC}"
        elif [ "$usage" -gt 60 ]; then
            echo -e "${YELLOW}$line${NC}"
        else
            echo -e "$line"
        fi
    done

    echo -e "\n${YELLOW}磁盘设备信息:${NC}"
    if command -v lsblk >/dev/null 2>&1; then
        lsblk -o NAME,SIZE,TYPE,MOUNTPOINT | column -t
    else
        fdisk -l 2>/dev/null | grep "Disk /"
    fi
}

show_network_info() {
    print_section "网络信息"

    echo -e "${YELLOW}网卡信息:${NC}"
    if command -v ip >/dev/null 2>&1; then
        ip addr show | awk '/^[0-9]+:/ {sub(/:/,"",$2); iface=$2} /inet / {print iface, $2}'
    else
        ifconfig | awk '/^[a-zA-Z0-9]+:/ {sub(/:/,"",$1); iface=$1} /inet addr:/ {print iface, $2}'
    fi

    echo -e "\n${YELLOW}路由信息:${NC}"
    if command -v ip >/dev/null 2>&1; then
        ip route show
    else
        route -n
    fi

    echo -e "\n${YELLOW}DNS配置:${NC}"
    if [ -f /etc/resolv.conf ]; then
        grep nameserver /etc/resolv.conf
    fi
}

show_process_info() {
    print_section "进程和服务信息"
    
    echo -e "${YELLOW}CPU占用TOP5进程:${NC}"
    ps aux --sort=-%cpu | head -6 | awk 'NR==1 {print $0} NR>1 {printf "%-10s %5s %5s %s\n", $1, $3, $4, $11}'

    echo -e "\n${YELLOW}内存占用TOP5进程:${NC}"
    ps aux --sort=-%mem | head -6 | awk 'NR==1 {print $0} NR>1 {printf "%-10s %5s %5s %s\n", $1, $3, $4, $11}'

    echo -e "\n${YELLOW}系统负载:${NC}"
    if [ -f /proc/loadavg ]; then
        read one five fifteen _ < /proc/loadavg
        echo "  1分钟负载: $one"
        echo "  5分钟负载: $five"
        echo "  15分钟负载: $fifteen"
    fi
}

show_security_info() {
    print_section "安全信息"
    
    echo -e "${YELLOW}登录用户:${NC}"
    who

    echo -e "\n${YELLOW}最近登录记录:${NC}"
    last | head -5

    echo -e "\n${YELLOW}失败登录尝试:${NC}"
    if [ -f /var/log/btmp ]; then
        lastb | head -5 2>/dev/null || echo "无法访问失败登录日志"
    else
        echo "未找到失败登录日志文件"
    fi

    echo -e "\n${YELLOW}开放端口:${NC}"
    if command -v ss >/dev/null 2>&1; then
        ss -tuln | grep LISTEN | head -10
    elif command -v netstat >/dev/null 2>&1; then
        netstat -tuln | grep LISTEN | head -10
    fi
}

network_diagnosis() {
    print_section "网络诊断工具"
    
    read -p "请输入要测试的主机/IP (默认: 8.8.8.8): " target
    target=${target:-8.8.8.8}
    
    echo -e "${YELLOW}Ping测试 $target:${NC}"
    ping -c 4 $target
    
    echo -e "\n${YELLOW}路由跟踪 $target:${NC}"
    if command -v traceroute >/dev/null 2>&1; then
        traceroute -m 10 $target
    elif command -v tracepath >/dev/null 2>&1; then
        tracepath $target
    else
        echo "traceroute/tracepath 未安装"
    fi
}

set_hostname() {
    print_section "设置主机名"
    
    echo -e "${YELLOW}当前主机名:${NC} $(hostname)"
    read -p "请输入新的主机名: " new_hostname
    
    if [ -n "$new_hostname" ]; then
        if command -v hostnamectl >/dev/null 2>&1; then
            sudo hostnamectl set-hostname "$new_hostname"
            echo -e "${GREEN}主机名已更新为: $new_hostname${NC}"
        else
            echo "$new_hostname" | sudo tee /etc/hostname > /dev/null
            hostname "$new_hostname"
            echo -e "${GREEN}主机名已更新为: $new_hostname${NC}"
            echo -e "${YELLOW}注意: 重启后生效${NC}"
        fi
    fi
}

show_system_services() {
    print_section "系统服务状态"

    if command -v systemctl >/dev/null 2>&1; then
        echo -e "${YELLOW}失败的服务:${NC}"
        systemctl --failed | grep -v "0 loaded units"

        echo -e "\n${YELLOW}运行中的服务:${NC}"
        systemctl list-units --type=service --state=running | head -10
    else
        echo -e "${YELLOW}系统服务 (SysV):${NC}"
        service --status-all 2>/dev/null
    fi
}

show_logs() {
    print_section "系统日志"
    
    echo -e "${YELLOW}最近的系统错误:${NC}"
    if command -v journalctl >/dev/null 2>&1; then
        journalctl -p err -n 10 --no-pager
    elif [ -f /var/log/syslog ]; then
        tail -20 /var/log/syslog | grep -i error
    elif [ -f /var/log/messages ]; then
        tail -20 /var/log/messages | grep -i error
    else
        echo "无法找到系统日志文件"
    fi
}

# ==========================================================
# 深度安全检查功能模块
# ==========================================================

deep_security_check() {
    print_section "深度安全检查"
    log_info "开始深度安全检查"
    
    check_suspicious_processes
    check_network_connections
    check_ssh_security
    check_file_permissions
    check_user_privileges
    check_cron_jobs
    check_failed_logins
    check_system_backdoors
}

check_suspicious_processes() {
    echo -e "\n${YELLOW}🔍 检查可疑进程...${NC}"
    
    # 检查CPU使用率过高的进程
    high_cpu=$(ps aux --sort=-%cpu | awk 'NR>1 && $3>50 {print $1, $3"% CPU", $11}' | head -5)
    if [ -n "$high_cpu" ]; then
        log_warning "发现高CPU使用率进程:"
        echo "$high_cpu" | while read line; do
            echo "  $line"
            log_warning "高CPU进程: $line"
        done
    fi
    
    # 检查可疑进程名
    suspicious_names="nc\|netcat\|wget\|curl.*sh\|python.*-c\|perl.*-e\|base64\|powershell"
    suspicious_procs=$(ps aux | grep -E "$suspicious_names" | grep -v grep)
    if [ -n "$suspicious_procs" ]; then
        log_critical "发现可疑进程:"
        echo "$suspicious_procs" | while read line; do
            echo "  $line"
            log_critical "可疑进程: $line"
        done
    fi
    
    # 检查无父进程的进程
    orphan_procs=$(ps -eo pid,ppid,cmd | awk '$2==1 && NR>1' | head -10)
    echo -e "\n${YELLOW}孤儿进程 (PPID=1):${NC}"
    echo "$orphan_procs"
}

check_network_connections() {
    echo -e "\n${YELLOW}🌐 检查网络连接...${NC}"
    
    # 检查异常网络连接
    if check_command ss; then
        # 检查大量ESTABLISHED连接
        established_count=$(ss -tun | grep ESTAB | wc -l)
        if [ "$established_count" -gt 100 ]; then
            log_warning "ESTABLISHED连接数过多: $established_count"
        fi
        
        # 检查异常端口连接
        echo -e "\n${YELLOW}外部连接统计:${NC}"
        ss -tun | grep ESTAB | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -nr | head -10
        
        # 检查可疑端口监听
        suspicious_ports=$(ss -tlnp | grep -E ':22[0-9][0-9]|:31[0-9][0-9]|:4444|:5555|:6666|:7777|:8888|:9999')
        if [ -n "$suspicious_ports" ]; then
            log_warning "发现可疑端口监听:"
            echo "$suspicious_ports"
        fi
    fi
}

check_ssh_security() {
    echo -e "\n${YELLOW}🔐 检查SSH安全配置...${NC}"
    
    if [ -f /etc/ssh/sshd_config ]; then
        # 检查root登录
        root_login=$(grep -i "^PermitRootLogin" /etc/ssh/sshd_config | awk '{print $2}')
        if [ "$root_login" = "yes" ]; then
            log_critical "SSH允许root直接登录"
        else
            log_success "SSH禁止root直接登录"
        fi
        
        # 检查密码认证
        password_auth=$(grep -i "^PasswordAuthentication" /etc/ssh/sshd_config | awk '{print $2}')
        if [ "$password_auth" = "yes" ]; then
            log_warning "SSH启用密码认证"
        fi
        
        # 检查空密码登录
        empty_pass=$(grep -i "^PermitEmptyPasswords" /etc/ssh/sshd_config | awk '{print $2}')
        if [ "$empty_pass" = "yes" ]; then
            log_critical "SSH允许空密码登录"
        fi
        
        # 检查SSH版本
        ssh_version=$(grep -i "^Protocol" /etc/ssh/sshd_config | awk '{print $2}')
        if [ "$ssh_version" = "1" ]; then
            log_critical "SSH使用不安全的协议版本1"
        fi
    fi
}

check_file_permissions() {
    echo -e "\n${YELLOW}📁 检查关键文件权限...${NC}"
    
    # 检查passwd和shadow文件权限
    if [ -f /etc/passwd ]; then
        passwd_perm=$(stat -c "%a" /etc/passwd)
        if [ "$passwd_perm" != "644" ]; then
            log_warning "/etc/passwd 权限异常: $passwd_perm (应为644)"
        fi
    fi
    
    if [ -f /etc/shadow ]; then
        shadow_perm=$(stat -c "%a" /etc/shadow)
        if [ "$shadow_perm" != "640" ] && [ "$shadow_perm" != "000" ]; then
            log_warning "/etc/shadow 权限异常: $shadow_perm (应为640)"
        fi
    fi
    
    # 检查SUID文件
    echo -e "\n${YELLOW}SUID文件:${NC}"
    find /usr -type f -perm -4000 2>/dev/null | head -10
    
    # 检查world-writable文件
    world_writable=$(find /etc /usr/bin /usr/sbin -type f -perm -002 2>/dev/null | head -5)
    if [ -n "$world_writable" ]; then
        log_warning "发现world-writable文件:"
        echo "$world_writable"
    fi
}

check_user_privileges() {
    echo -e "\n${YELLOW}👥 检查用户权限...${NC}"
    
    # 检查UID为0的用户
    uid_zero=$(awk -F: '$3==0 {print $1}' /etc/passwd)
    echo -e "${YELLOW}UID为0的用户:${NC} $uid_zero"
    if [ "$(echo "$uid_zero" | wc -w)" -gt 1 ]; then
        log_warning "发现多个UID为0的用户: $uid_zero"
    fi
    
    # 检查sudo权限
    if [ -f /etc/sudoers ]; then
        echo -e "\n${YELLOW}sudo配置:${NC}"
        grep -v "^#\|^$" /etc/sudoers | grep -E "ALL=|NOPASSWD" | head -5
    fi
    
    # 检查无密码用户
    no_passwd=$(awk -F: '$2=="" {print $1}' /etc/shadow 2>/dev/null)
    if [ -n "$no_passwd" ]; then
        log_critical "发现无密码用户: $no_passwd"
    fi
}

check_cron_jobs() {
    echo -e "\n${YELLOW}⏰ 检查定时任务...${NC}"
    
    # 检查系统crontab
    if [ -f /etc/crontab ]; then
        echo -e "${YELLOW}系统crontab:${NC}"
        grep -v "^#\|^$" /etc/crontab
    fi
    
    # 检查用户crontab
    for user in $(cut -d: -f1 /etc/passwd); do
        user_cron=$(crontab -l -u "$user" 2>/dev/null)
        if [ -n "$user_cron" ]; then
            echo -e "\n${YELLOW}用户 $user 的crontab:${NC}"
            echo "$user_cron"
        fi
    done | head -20
    
    # 检查cron.d目录
    if [ -d /etc/cron.d ]; then
        cron_d_files=$(ls /etc/cron.d/ 2>/dev/null)
        if [ -n "$cron_d_files" ]; then
            echo -e "\n${YELLOW}/etc/cron.d 文件:${NC}"
            echo "$cron_d_files"
        fi
    fi
}

check_failed_logins() {
    echo -e "\n${YELLOW}🚫 检查失败登录...${NC}"
    
    # 检查最近的失败登录
    if [ -f /var/log/btmp ]; then
        failed_count=$(lastb -n 50 2>/dev/null | wc -l)
        if [ "$failed_count" -gt "$FAILED_LOGIN_THRESHOLD" ]; then
            log_warning "最近失败登录次数过多: $failed_count"
        fi
        
        echo -e "${YELLOW}最近失败登录IP统计:${NC}"
        lastb -n 100 2>/dev/null | awk '{print $3}' | grep -E '^[0-9]+\.' | sort | uniq -c | sort -nr | head -5
    fi
    
    # 检查auth.log中的失败登录
    if [ -f /var/log/auth.log ]; then
        recent_failures=$(grep "Failed password" /var/log/auth.log | tail -10)
        if [ -n "$recent_failures" ]; then
            echo -e "\n${YELLOW}最近密码失败尝试:${NC}"
            echo "$recent_failures" | cut -d' ' -f1-3,9-
        fi
    fi
}

check_system_backdoors() {
    echo -e "\n${YELLOW}🕵️  检查潜在后门...${NC}"
    
    # 检查异常的启动脚本
    if [ -d /etc/init.d ]; then
        echo -e "${YELLOW}检查启动脚本:${NC}"
        find /etc/init.d -type f -name "*.*" 2>/dev/null | head -5
    fi
    
    # 检查.bash_profile中的异常内容
    for home_dir in /home/* /root; do
        if [ -f "$home_dir/.bash_profile" ]; then
            # 只检查非注释行中的可疑命令
            suspicious_bash=$(grep -E "wget|curl|nc|netcat" "$home_dir/.bash_profile" 2>/dev/null | grep -v "^#" | grep -v "^[[:space:]]*#")
            if [ -n "$suspicious_bash" ]; then
                log_warning "在 $home_dir/.bash_profile 中发现可疑内容: $suspicious_bash"
            fi
        fi
    done
    
    # 检查隐藏文件
    hidden_files=$(find /tmp /var/tmp -name ".*" -type f 2>/dev/null | head -10)
    if [ -n "$hidden_files" ]; then
        echo -e "\n${YELLOW}临时目录中的隐藏文件:${NC}"
        echo "$hidden_files"
    fi
}

# ==========================================================
# 性能监控和趋势分析模块
# ==========================================================

performance_monitoring() {
    print_section "性能监控与分析"
    log_info "开始性能监控分析"
    
    check_cpu_performance
    check_memory_performance
    check_disk_performance
    check_network_performance
    check_system_load
    check_io_performance
}

check_cpu_performance() {
    echo -e "\n${YELLOW}🖥️  CPU性能分析...${NC}"
    
    # CPU使用率
    if check_command vmstat; then
        echo -e "${YELLOW}CPU使用率统计 (5次采样):${NC}"
        vmstat 1 5 | tail -5 | awk 'NR>1 {
            cpu_idle = $15
            cpu_used = 100 - cpu_idle
            if (cpu_used > '$CPU_THRESHOLD') status = " ⚠️ "
            else status = " ✅ "
            printf "%s CPU使用率: %.1f%% (空闲: %.1f%%)\n", status, cpu_used, cpu_idle
        }'
    fi
    
    # CPU核心温度 (如果可用)
    if [ -d /sys/class/thermal ]; then
        echo -e "\n${YELLOW}CPU温度:${NC}"
        for thermal in /sys/class/thermal/thermal_zone*/temp; do
            if [ -r "$thermal" ]; then
                temp=$(cat "$thermal" 2>/dev/null)
                if [ -n "$temp" ] && [ "$temp" -gt 0 ]; then
                    temp_c=$((temp / 1000))
                    if [ "$temp_c" -gt 80 ]; then
                        log_warning "CPU温度过高: ${temp_c}°C"
                        echo -e "  🔥 温度: ${temp_c}°C"
                    elif [ "$temp_c" -gt 70 ]; then
                        echo -e "  ⚠️  温度: ${temp_c}°C"
                    else
                        echo -e "  ✅ 温度: ${temp_c}°C"
                    fi
                fi
            fi
        done
    fi
    
    # CPU负载历史
    if [ -f /proc/loadavg ]; then
        read one five fifteen _ < /proc/loadavg
        cpu_cores=$(nproc)
        echo -e "\n${YELLOW}系统负载分析:${NC}"
        
        # 计算负载百分比
        load_1_pct=$(echo "$one $cpu_cores" | awk '{printf "%.1f", ($1/$2)*100}')
        load_5_pct=$(echo "$five $cpu_cores" | awk '{printf "%.1f", ($1/$2)*100}')
        load_15_pct=$(echo "$fifteen $cpu_cores" | awk '{printf "%.1f", ($1/$2)*100}')
        
        # 判断负载状态
        load_check=$(echo "$one $LOAD_THRESHOLD" | awk '{if($1 > $2) print "high"; else print "ok"}')
        if [ "$load_check" = "high" ]; then
            log_warning "1分钟负载过高: $one (${load_1_pct}%)"
            echo -e "  🚨 1分钟负载: $one (${load_1_pct}%)"
        else
            echo -e "  ✅ 1分钟负载: $one (${load_1_pct}%)"
        fi
        
        echo -e "     5分钟负载: $five (${load_5_pct}%)"
        echo -e "     15分钟负载: $fifteen (${load_15_pct}%)"
    fi
}

check_memory_performance() {
    echo -e "\n${YELLOW}💾 内存性能分析...${NC}"
    
    if [ -f /proc/meminfo ]; then
        # 内存详细信息
        mem_total=$(awk '/MemTotal/ {print $2}' /proc/meminfo)
        mem_free=$(awk '/MemFree/ {print $2}' /proc/meminfo)
        mem_available=$(awk '/MemAvailable/ {print $2}' /proc/meminfo)
        mem_buffers=$(awk '/Buffers/ {print $2}' /proc/meminfo)
        mem_cached=$(awk '/^Cached/ {print $2}' /proc/meminfo)
        swap_total=$(awk '/SwapTotal/ {print $2}' /proc/meminfo)
        swap_free=$(awk '/SwapFree/ {print $2}' /proc/meminfo)
        
        # 计算使用率
        mem_used=$((mem_total - mem_available))
        mem_used_pct=$((mem_used * 100 / mem_total))
        swap_used=$((swap_total - swap_free))
        
        echo -e "${YELLOW}内存使用详情:${NC}"
        echo "  总内存: $(echo $mem_total | awk '{printf "%.1f GB", $1/1024/1024}')"
        echo "  已使用: $(echo $mem_used | awk '{printf "%.1f GB", $1/1024/1024}') (${mem_used_pct}%)"
        echo "  可用内存: $(echo $mem_available | awk '{printf "%.1f GB", $1/1024/1024}')"
        echo "  缓冲区: $(echo $mem_buffers | awk '{printf "%.1f MB", $1/1024}')"
        echo "  缓存: $(echo $mem_cached | awk '{printf "%.1f GB", $1/1024/1024}')"
        
        # 内存使用率警告
        if [ "$mem_used_pct" -gt "$MEM_THRESHOLD" ]; then
            log_warning "内存使用率过高: ${mem_used_pct}%"
        fi
        
        # Swap检查
        if [ "$swap_total" -gt 0 ]; then
            swap_used_pct=$((swap_used * 100 / swap_total))
            echo -e "\n${YELLOW}Swap使用情况:${NC}"
            echo "  Swap总量: $(echo $swap_total | awk '{printf "%.1f GB", $1/1024/1024}')"
            echo "  Swap已使用: $(echo $swap_used | awk '{printf "%.1f GB", $1/1024/1024}') (${swap_used_pct}%)"
            
            if [ "$swap_used_pct" -gt 50 ]; then
                log_warning "Swap使用率过高: ${swap_used_pct}%"
            fi
        fi
        
        # 内存碎片化检查
        if [ -f /proc/buddyinfo ]; then
            echo -e "\n${YELLOW}内存碎片化信息:${NC}"
            free_pages=$(awk '/^Node/ {sum+=$8} END {print sum}' /proc/buddyinfo 2>/dev/null || echo "0")
            if [ "$free_pages" -lt 1000 ]; then
                log_warning "大页面内存不足，可能存在内存碎片化"
            fi
        fi
    fi
}

check_disk_performance() {
    echo -e "\n${YELLOW}💽 磁盘性能分析...${NC}"
    
    # 磁盘使用率检查 (带颜色警告)
    echo -e "${YELLOW}磁盘空间使用率:${NC}"
    df -h | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{
        print $0 " " $5
    }' | while read line; do
        usage=$(echo $line | awk '{print $6}' | sed 's/%//')
        if [ "$usage" -gt '$DISK_THRESHOLD' ]; then
            echo -e "  🚨 $line"
            echo "[WARNING] 磁盘使用率过高: $line" >> "'$LOG_FILE'"
        elif [ "$usage" -gt 70 ]; then
            echo -e "  ⚠️  $line"
        else
            echo -e "  ✅ $line"
        fi
    done
    
    # I/O统计
    if check_command iostat; then
        echo -e "\n${YELLOW}磁盘I/O统计:${NC}"
        iostat -x 1 3 | tail -n +4 | awk '/^[a-z]/ {
            if (NR > 1) {
                printf "  设备: %-8s 读: %8.1f KB/s 写: %8.1f KB/s 使用率: %6.1f%%\n", 
                $1, $6, $7, $10
                if ($10 > 80) print "    ⚠️  I/O使用率过高"
            }
        }'
    fi
    
    # 检查磁盘错误
    echo -e "\n${YELLOW}磁盘健康状态:${NC}"
    if check_command smartctl; then
        for disk in $(lsblk -d -o NAME | grep -E '^[a-z]+$'); do
            smart_status=$(smartctl -H /dev/$disk 2>/dev/null | grep "SMART overall-health")
            if [ -n "$smart_status" ]; then
                echo "  /dev/$disk: $smart_status"
                if echo "$smart_status" | grep -q "FAILED"; then
                    log_critical "磁盘 /dev/$disk SMART检查失败"
                fi
            fi
        done
    else
        echo "  SMART工具未安装，无法检查磁盘健康状态"
    fi
    
    # 检查最大文件
    echo -e "\n${YELLOW}大文件检查 (>100MB):${NC}"
    find /var/log -type f -size +100M 2>/dev/null | head -5 | while read file; do
        size=$(du -h "$file" | cut -f1)
        echo "  $file ($size)"
        if [[ $size =~ [0-9]+G ]]; then
            log_warning "发现超大日志文件: $file ($size)"
        fi
    done
}

check_network_performance() {
    echo -e "\n${YELLOW}🌐 网络性能分析...${NC}"
    
    # 网络接口统计
    if check_command ip; then
        echo -e "${YELLOW}网络接口流量统计:${NC}"
        for interface in $(ip link show | awk -F: '$0 !~ "lo|vir|docker|br-"{print $2}' | tr -d ' '); do
            if [ -f "/sys/class/net/$interface/statistics/rx_bytes" ]; then
                rx_bytes=$(cat /sys/class/net/$interface/statistics/rx_bytes)
                tx_bytes=$(cat /sys/class/net/$interface/statistics/tx_bytes)
                rx_packets=$(cat /sys/class/net/$interface/statistics/rx_packets)
                tx_packets=$(cat /sys/class/net/$interface/statistics/tx_packets)
                rx_errors=$(cat /sys/class/net/$interface/statistics/rx_errors)
                tx_errors=$(cat /sys/class/net/$interface/statistics/tx_errors)
                
                echo "  接口: $interface"
                echo "    接收: $(echo $rx_bytes | awk '{printf "%.1f MB", $1/1024/1024}') ($rx_packets 包)"
                echo "    发送: $(echo $tx_bytes | awk '{printf "%.1f MB", $1/1024/1024}') ($tx_packets 包)"
                
                if [ "$rx_errors" -gt 0 ] || [ "$tx_errors" -gt 0 ]; then
                    log_warning "网络接口 $interface 存在错误: 接收错误 $rx_errors, 发送错误 $tx_errors"
                    echo "    ⚠️  错误: 接收 $rx_errors, 发送 $tx_errors"
                fi
            fi
        done
    fi
    
    # TCP连接状态统计
    echo -e "\n${YELLOW}TCP连接状态统计:${NC}"
    if check_command ss; then
        ss -s | grep -E "TCP:|UDP:" | while read line; do
            echo "  $line"
        done
        
        # 检查TIME_WAIT连接数
        time_wait_count=$(ss -tan | grep TIME-WAIT | wc -l)
        if [ "$time_wait_count" -gt 1000 ]; then
            log_warning "TIME_WAIT连接数过多: $time_wait_count"
        fi
        echo "  TIME_WAIT连接数: $time_wait_count"
    fi
    
    # 网络延迟测试
    echo -e "\n${YELLOW}网络连通性测试:${NC}"
    for target in 8.8.8.8 114.114.114.114; do
        ping_result=$(ping -c 3 -W 2 $target 2>/dev/null | tail -1)
        if [ -n "$ping_result" ]; then
            avg_time=$(echo "$ping_result" | awk -F'/' '{print $5}')
            echo "  到 $target 平均延迟: ${avg_time}ms"
            delay_check=$(echo "$avg_time" | awk '{if($1 > 100) print "high"; else print "ok"}')
            if [ "$delay_check" = "high" ]; then
                log_warning "到 $target 网络延迟过高: ${avg_time}ms"
            fi
        else
            log_critical "无法连接到 $target"
        fi
    done
}

check_system_load() {
    echo -e "\n${YELLOW}⚡ 系统负载趋势...${NC}"
    
    # 如果有sar命令，显示历史负载
    if check_command sar; then
        echo -e "${YELLOW}最近24小时平均负载:${NC}"
        sar -q | tail -5 | awk 'NR>1 && !/Average/ {
            printf "  %s %s - 1分钟: %s, 5分钟: %s, 15分钟: %s\n", 
            $1, $2, $4, $5, $6
        }'
    fi
    
    # 当前最消耗资源的进程
    echo -e "\n${YELLOW}资源消耗TOP进程:${NC}"
    echo -e "${YELLOW}  CPU TOP 3:${NC}"
    ps aux --sort=-%cpu | head -4 | tail -3 | awk '{
        printf "    %s: %.1f%% CPU, %.1f%% MEM\n", $11, $3, $4
    }'
    
    echo -e "${YELLOW}  内存 TOP 3:${NC}"
    ps aux --sort=-%mem | head -4 | tail -3 | awk '{
        printf "    %s: %.1f%% MEM, %.1f%% CPU\n", $11, $4, $3
    }'
}

check_io_performance() {
    echo -e "\n${YELLOW}📊 I/O性能分析...${NC}"
    
    # 检查I/O等待
    if check_command vmstat; then
        echo -e "${YELLOW}I/O等待统计:${NC}"
        vmstat 1 5 | tail -5 | awk 'NR>1 {
            iowait = $16
            if (iowait > 20) status = " 🚨"
            else if (iowait > 10) status = " ⚠️ "
            else status = " ✅"
            printf "%s I/O等待: %s%%\n", status, iowait
        }'
    fi
    
    # 检查进程I/O
    if [ -f /proc/diskstats ]; then
        echo -e "\n${YELLOW}磁盘I/O活动:${NC}"
        awk '$4 ~ /^[a-z]+$/ && $4 !~ /loop|ram/ {
            printf "  %s: 读 %d 次, 写 %d 次\n", $4, $8, $12
        }' /proc/diskstats | head -5
    fi
}

# ==========================================================
# 配置合规性检查模块
# ==========================================================

compliance_check() {
    print_section "系统配置合规性检查"
    log_info "开始配置合规性检查"
    
    check_system_parameters
    check_security_settings
    check_service_configuration
    check_firewall_settings
    check_selinux_status
    check_password_policy
    check_system_hardening
}

check_system_parameters() {
    echo -e "\n${YELLOW}⚙️  系统参数检查...${NC}"
    
    # 检查重要的内核参数
    echo -e "${YELLOW}关键内核参数:${NC}"
    
    # 网络安全参数
    params=(
        "net.ipv4.ip_forward"
        "net.ipv4.conf.all.send_redirects"
        "net.ipv4.conf.all.accept_redirects"
        "net.ipv4.conf.all.accept_source_route"
        "net.ipv4.tcp_syncookies"
        "net.ipv4.icmp_echo_ignore_broadcasts"
        "kernel.randomize_va_space"
        "kernel.exec-shield"
    )
    
    for param in "${params[@]}"; do
        value=$(sysctl -n "$param" 2>/dev/null)
        if [ -n "$value" ]; then
            case $param in
                "net.ipv4.ip_forward")
                    if [ "$value" = "1" ]; then
                        log_warning "IP转发已启用: $param = $value"
                        echo -e "  ⚠️  $param = $value (建议关闭)"
                    else
                        echo -e "  ✅ $param = $value"
                    fi
                    ;;
                "net.ipv4.tcp_syncookies")
                    if [ "$value" = "1" ]; then
                        echo -e "  ✅ $param = $value"
                    else
                        log_warning "TCP SYN cookies未启用: $param = $value"
                        echo -e "  ⚠️  $param = $value (建议启用)"
                    fi
                    ;;
                "kernel.randomize_va_space")
                    if [ "$value" = "2" ]; then
                        echo -e "  ✅ $param = $value"
                    else
                        log_warning "地址空间随机化未完全启用: $param = $value"
                        echo -e "  ⚠️  $param = $value (建议设为2)"
                    fi
                    ;;
                *)
                    echo -e "  📋 $param = $value"
                    ;;
            esac
        fi
    done
    
    # 检查文件描述符限制
    echo -e "\n${YELLOW}系统限制:${NC}"
    ulimit_hard=$(ulimit -Hn)
    ulimit_soft=$(ulimit -Sn)
    echo -e "  文件描述符限制: 软限制 $ulimit_soft, 硬限制 $ulimit_hard"
    if [ "$ulimit_soft" -lt 1024 ]; then
        log_warning "文件描述符软限制过低: $ulimit_soft"
    fi
}

check_security_settings() {
    echo -e "\n${YELLOW}🔒 安全设置检查...${NC}"
    
    # 检查umask设置
    current_umask=$(umask)
    echo -e "${YELLOW}默认umask:${NC} $current_umask"
    if [ "$current_umask" = "0002" ] || [ "$current_umask" = "002" ]; then
        log_warning "umask设置可能不够安全: $current_umask (建议022)"
    fi
    
    # 检查重要目录权限
    echo -e "\n${YELLOW}关键目录权限:${NC}"
    critical_dirs=("/etc" "/usr/bin" "/usr/sbin" "/bin" "/sbin")
    for dir in "${critical_dirs[@]}"; do
        if [ -d "$dir" ]; then
            perm=$(stat -c "%a" "$dir")
            owner=$(stat -c "%U:%G" "$dir")
            echo -e "  $dir: $perm ($owner)"
            if [ "$perm" -gt 755 ]; then
                log_warning "目录 $dir 权限过于宽松: $perm"
            fi
        fi
    done
    
    # 检查/tmp目录权限
    if [ -d /tmp ]; then
        tmp_perm=$(stat -c "%a" /tmp)
        if [ "$tmp_perm" != "1777" ]; then
            log_warning "/tmp 目录权限异常: $tmp_perm (应为1777)"
        else
            log_success "/tmp 目录权限正确: $tmp_perm"
        fi
    fi
    
    # 检查敏感文件权限
    echo -e "\n${YELLOW}敏感文件权限:${NC}"
    sensitive_files=("/etc/passwd" "/etc/shadow" "/etc/gshadow" "/etc/group")
    for file in "${sensitive_files[@]}"; do
        if [ -f "$file" ]; then
            perm=$(stat -c "%a" "$file")
            owner=$(stat -c "%U:%G" "$file")
            echo -e "  $file: $perm ($owner)"
            
            case $(basename "$file") in
                "passwd"|"group")
                    if [ "$perm" != "644" ]; then
                        log_warning "$file 权限异常: $perm (应为644)"
                    fi
                    ;;
                "shadow"|"gshadow")
                    if [ "$perm" != "640" ] && [ "$perm" != "000" ]; then
                        log_warning "$file 权限异常: $perm (应为640)"
                    fi
                    ;;
            esac
        fi
    done
}

check_service_configuration() {
    echo -e "\n${YELLOW}🔧 服务配置检查...${NC}"
    
    # 检查不安全的服务
    unsafe_services=("telnet" "ftp" "rsh" "rlogin" "tftp" "finger")
    echo -e "${YELLOW}不安全服务检查:${NC}"
    for service in "${unsafe_services[@]}"; do
        if check_command systemctl; then
            status=$(systemctl is-active "$service" 2>/dev/null)
            if [ "$status" = "active" ]; then
                log_critical "发现运行中的不安全服务: $service"
                echo -e "  🚨 $service: 运行中"
            else
                echo -e "  ✅ $service: 未运行"
            fi
        fi
    done
    
    # 检查SSH服务配置
    if [ -f /etc/ssh/sshd_config ]; then
        echo -e "\n${YELLOW}SSH配置详细检查:${NC}"
        
        # 检查端口
        ssh_port=$(grep -E "^Port" /etc/ssh/sshd_config | awk '{print $2}')
        if [ -n "$ssh_port" ] && [ "$ssh_port" != "22" ]; then
            log_success "SSH端口已修改: $ssh_port"
        else
            log_warning "SSH仍使用默认端口22"
        fi
        
        # 检查其他SSH安全设置
        ssh_settings=(
            "MaxAuthTries:6"
            "ClientAliveInterval:300"
            "ClientAliveCountMax:0"
            "LoginGraceTime:60"
            "MaxStartups:10:30:60"
        )
        
        for setting in "${ssh_settings[@]}"; do
            key=$(echo "$setting" | cut -d: -f1)
            recommended=$(echo "$setting" | cut -d: -f2)
            current=$(grep -E "^$key" /etc/ssh/sshd_config | awk '{print $2}')
            if [ -n "$current" ]; then
                echo -e "  $key: $current"
                if [ "$current" != "$recommended" ]; then
                    echo -e "    💡 建议值: $recommended"
                fi
            else
                echo -e "  $key: 未设置 (建议: $recommended)"
            fi
        done
    fi
    
    # 检查时间同步服务
    echo -e "\n${YELLOW}时间同步服务:${NC}"
    if check_command systemctl; then
        for ntp_service in ntp ntpd chronyd systemd-timesyncd; do
            status=$(systemctl is-active "$ntp_service" 2>/dev/null)
            if [ "$status" = "active" ]; then
                log_success "时间同步服务运行中: $ntp_service"
                echo -e "  ✅ $ntp_service: 运行中"
                break
            fi
        done
    fi
}

check_firewall_settings() {
    echo -e "\n${YELLOW}🛡️  防火墙配置检查...${NC}"
    
    # 检查iptables
    if check_command iptables; then
        rule_count=$(iptables -L | wc -l)
        echo -e "${YELLOW}iptables规则数:${NC} $rule_count"
        if [ "$rule_count" -lt 10 ]; then
            log_warning "iptables规则可能过于简单"
        fi
        
        # 检查默认策略
        default_input=$(iptables -L | grep "Chain INPUT" | awk '{print $4}')
        default_forward=$(iptables -L | grep "Chain FORWARD" | awk '{print $4}')
        default_output=$(iptables -L | grep "Chain OUTPUT" | awk '{print $4}')
        
        echo -e "  默认策略: INPUT($default_input) FORWARD($default_forward) OUTPUT($default_output)"
        
        if [ "$default_input" = "(policy ACCEPT)" ]; then
            log_warning "INPUT链默认策略为ACCEPT，安全性较低"
        fi
    fi
    
    # 检查firewalld
    if check_command firewall-cmd; then
        firewalld_status=$(systemctl is-active firewalld 2>/dev/null)
        if [ "$firewalld_status" = "active" ]; then
            log_success "firewalld服务运行中"
            default_zone=$(firewall-cmd --get-default-zone 2>/dev/null)
            echo -e "  默认区域: $default_zone"
            
            active_zones=$(firewall-cmd --get-active-zones 2>/dev/null)
            echo -e "  活跃区域:\n$active_zones" | head -5
        else
            echo -e "  firewalld: 未运行"
        fi
    fi
    
    # 检查ufw (Ubuntu)
    if check_command ufw; then
        ufw_status=$(ufw status 2>/dev/null | head -1)
        echo -e "  ufw状态: $ufw_status"
        if echo "$ufw_status" | grep -q "inactive"; then
            log_warning "ufw防火墙未启用"
        fi
    fi
}

check_selinux_status() {
    echo -e "\n${YELLOW}🔐 SELinux状态检查...${NC}"
    
    if check_command sestatus; then
        selinux_status=$(sestatus | grep "SELinux status" | cut -d: -f2 | tr -d ' ')
        selinux_mode=$(sestatus | grep "Current mode" | cut -d: -f2 | tr -d ' ')
        
        echo -e "  SELinux状态: $selinux_status"
        echo -e "  当前模式: $selinux_mode"
        
        if [ "$selinux_status" = "enabled" ]; then
            if [ "$selinux_mode" = "enforcing" ]; then
                log_success "SELinux已启用并处于强制模式"
            elif [ "$selinux_mode" = "permissive" ]; then
                log_warning "SELinux处于宽松模式"
            fi
        else
            log_warning "SELinux未启用"
        fi
        
        # 检查SELinux拒绝记录
        if [ -f /var/log/audit/audit.log ]; then
            recent_denials=$(grep "avc.*denied" /var/log/audit/audit.log | tail -5 | wc -l)
            if [ "$recent_denials" -gt 0 ]; then
                log_info "最近有 $recent_denials 条SELinux拒绝记录"
            fi
        fi
    else
        echo -e "  SELinux工具未安装"
    fi
}

check_password_policy() {
    echo -e "\n${YELLOW}🔑 密码策略检查...${NC}"
    
    # 检查/etc/login.defs
    if [ -f /etc/login.defs ]; then
        echo -e "${YELLOW}密码策略设置:${NC}"
        
        # 密码相关参数
        pass_max_days=$(grep "^PASS_MAX_DAYS" /etc/login.defs | awk '{print $2}')
        pass_min_days=$(grep "^PASS_MIN_DAYS" /etc/login.defs | awk '{print $2}')
        pass_warn_age=$(grep "^PASS_WARN_AGE" /etc/login.defs | awk '{print $2}')
        pass_min_len=$(grep "^PASS_MIN_LEN" /etc/login.defs | awk '{print $2}')
        
        echo -e "  密码最大天数: ${pass_max_days:-未设置}"
        echo -e "  密码最小天数: ${pass_min_days:-未设置}"
        echo -e "  密码警告天数: ${pass_warn_age:-未设置}"
        echo -e "  密码最小长度: ${pass_min_len:-未设置}"
        
        # 检查密码策略是否合理
        if [ -n "$pass_max_days" ] && [ "$pass_max_days" -gt 90 ]; then
            log_warning "密码最大天数过长: $pass_max_days (建议≤90天)"
        fi
        
        if [ -n "$pass_min_len" ] && [ "$pass_min_len" -lt 8 ]; then
            log_warning "密码最小长度过短: $pass_min_len (建议≥8位)"
        fi
    fi
    
    # 检查PAM密码复杂度
    if [ -f /etc/pam.d/common-password ] || [ -f /etc/pam.d/system-auth ]; then
        echo -e "\n${YELLOW}PAM密码复杂度检查:${NC}"
        
        pam_files=("/etc/pam.d/common-password" "/etc/pam.d/system-auth" "/etc/pam.d/password-auth")
        for pam_file in "${pam_files[@]}"; do
            if [ -f "$pam_file" ]; then
                # 检查是否启用了密码复杂度检查
                if grep -q "pam_pwquality" "$pam_file" || grep -q "pam_cracklib" "$pam_file"; then
                    log_success "密码复杂度检查已启用 ($pam_file)"
                else
                    log_warning "密码复杂度检查未启用 ($pam_file)"
                fi
                break
            fi
        done
    fi
}

check_system_hardening() {
    echo -e "\n${YELLOW}🛠️  系统加固检查...${NC}"
    
    # 检查是否禁用了不必要的文件系统
    echo -e "${YELLOW}文件系统检查:${NC}"
    unused_fs=("cramfs" "freevxfs" "jffs2" "hfs" "hfsplus" "squashfs" "udf")
    for fs in "${unused_fs[@]}"; do
        if lsmod | grep -q "^$fs"; then
            log_warning "发现可能不需要的文件系统模块: $fs"
        fi
    done
    
    # 检查core dump设置
    echo -e "\n${YELLOW}Core dump设置:${NC}"
    core_limit=$(ulimit -c)
    echo -e "  当前core文件大小限制: $core_limit"
    if [ "$core_limit" != "0" ]; then
        log_warning "Core dump未完全禁用"
    else
        log_success "Core dump已禁用"
    fi
    
    # 检查是否有不必要的SUID文件
    echo -e "\n${YELLOW}可疑SUID文件检查:${NC}"
    suspicious_suid=$(find /usr -type f -perm -4000 2>/dev/null | grep -E "(nc|netcat|wget|curl)" | head -3)
    if [ -n "$suspicious_suid" ]; then
        log_warning "发现可疑的SUID文件:"
        echo "$suspicious_suid"
    else
        echo -e "  ✅ 未发现明显可疑的SUID文件"
    fi
    
    # 检查系统账户
    echo -e "\n${YELLOW}系统账户检查:${NC}"
    shell_users=$(awk -F: '$7 ~ /bash|sh/ && $3 >= 1000 {print $1}' /etc/passwd | wc -l)
    echo -e "  有shell的普通用户数: $shell_users"
    
    # 检查空密码账户
    empty_passwd=$(awk -F: '$2 == "" {print $1}' /etc/shadow 2>/dev/null)
    if [ -n "$empty_passwd" ]; then
        log_critical "发现空密码账户: $empty_passwd"
    else
        log_success "无空密码账户"
    fi
}

generate_html_report() {
    print_section "生成巡检报告"
    
    cat > "$HTML_REPORT" << EOF
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Linux系统深度巡检报告</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; background-color: #f5f5f5; }
        .container { max-width: 1200px; margin: 0 auto; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        .header { text-align: center; border-bottom: 2px solid #007acc; padding-bottom: 20px; margin-bottom: 30px; }
        .title { color: #007acc; margin: 0; }
        .subtitle { color: #666; margin: 5px 0; }
        .section { margin-bottom: 30px; }
        .section-title { color: #007acc; border-left: 4px solid #007acc; padding-left: 10px; margin-bottom: 15px; }
        .info-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; }
        .info-card { background: #f8f9fa; padding: 15px; border-radius: 6px; border-left: 4px solid #28a745; }
        .warning-card { background: #fff3cd; border-left-color: #ffc107; }
        .critical-card { background: #f8d7da; border-left-color: #dc3545; }
        .status-ok { color: #28a745; font-weight: bold; }
        .status-warning { color: #ffc107; font-weight: bold; }
        .status-critical { color: #dc3545; font-weight: bold; }
        .metric { display: flex; justify-content: space-between; margin: 5px 0; }
        .footer { text-align: center; margin-top: 30px; color: #666; font-size: 12px; }
        table { width: 100%; border-collapse: collapse; margin: 10px 0; }
        th, td { padding: 8px; border: 1px solid #ddd; text-align: left; }
        th { background-color: #f1f1f1; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1 class="title">Linux系统深度巡检报告</h1>
            <p class="subtitle">主机: $(hostname) | 生成时间: $(date)</p>
            <p class="subtitle">巡检工具版本: $SCRIPT_VERSION</p>
        </div>

        <div class="section">
            <h2 class="section-title">📊 系统概览</h2>
            <div class="info-grid">
                <div class="info-card">
                    <h3>系统信息</h3>
                    <div class="metric"><span>操作系统:</span><span>$(cat /etc/os-release | grep PRETTY_NAME | cut -d'"' -f2)</span></div>
                    <div class="metric"><span>内核版本:</span><span>$(uname -r)</span></div>
                    <div class="metric"><span>运行时间:</span><span>$(uptime -p 2>/dev/null || uptime)</span></div>
                </div>
                <div class="info-card">
                    <h3>硬件信息</h3>
                    <div class="metric"><span>CPU:</span><span>$(grep "model name" /proc/cpuinfo | head -1 | cut -d: -f2 | sed 's/^ *//')</span></div>
                    <div class="metric"><span>CPU核心:</span><span>$(nproc)</span></div>
                    <div class="metric"><span>内存:</span><span>$(awk '/MemTotal/ {printf "%.1f GB", $2/1024/1024}' /proc/meminfo)</span></div>
                </div>
            </div>
        </div>

        <div class="section">
            <h2 class="section-title">⚠️ 巡检发现的问题</h2>
            <div id="issues">
EOF

    # 添加警告和错误信息到报告
    if [ -f "$LOG_FILE" ]; then
        warnings=$(grep "\[WARNING\]" "$LOG_FILE" | wc -l)
        criticals=$(grep "\[CRITICAL\]" "$LOG_FILE" | wc -l)
        
        if [ "$warnings" -gt 0 ] || [ "$criticals" -gt 0 ]; then
            echo "                <div class=\"info-grid\">" >> "$HTML_REPORT"
            
            if [ "$criticals" -gt 0 ]; then
                echo "                    <div class=\"info-card critical-card\">" >> "$HTML_REPORT"
                echo "                        <h3 class=\"status-critical\">🚨 严重问题 ($criticals 个)</h3>" >> "$HTML_REPORT"
                grep "\[CRITICAL\]" "$LOG_FILE" | while read line; do
                    issue=$(echo "$line" | cut -d']' -f2- | sed 's/^ *//')
                    echo "                        <div>• $issue</div>" >> "$HTML_REPORT"
                done
                echo "                    </div>" >> "$HTML_REPORT"
            fi
            
            if [ "$warnings" -gt 0 ]; then
                echo "                    <div class=\"info-card warning-card\">" >> "$HTML_REPORT"
                echo "                        <h3 class=\"status-warning\">⚠️ 警告问题 ($warnings 个)</h3>" >> "$HTML_REPORT"
                grep "\[WARNING\]" "$LOG_FILE" | while read line; do
                    issue=$(echo "$line" | cut -d']' -f2- | sed 's/^ *//')
                    echo "                        <div>• $issue</div>" >> "$HTML_REPORT"
                done
                echo "                    </div>" >> "$HTML_REPORT"
            fi
            
            echo "                </div>" >> "$HTML_REPORT"
        else
            echo "                <div class=\"info-card\">" >> "$HTML_REPORT"
            echo "                    <h3 class=\"status-ok\">✅ 未发现重大问题</h3>" >> "$HTML_REPORT"
            echo "                    <p>系统巡检完成，未发现需要立即处理的安全或性能问题。</p>" >> "$HTML_REPORT"
            echo "                </div>" >> "$HTML_REPORT"
        fi
    fi

    cat >> "$HTML_REPORT" << EOF
            </div>
        </div>

        <div class="section">
            <h2 class="section-title">📈 性能指标</h2>
            <div class="info-grid">
                <div class="info-card">
                    <h3>CPU使用率</h3>
                    <div class="metric"><span>当前负载:</span><span>$(cat /proc/loadavg | cut -d' ' -f1-3)</span></div>
                    <div class="metric"><span>CPU核心数:</span><span>$(nproc)</span></div>
                </div>
                <div class="info-card">
                    <h3>内存使用</h3>
EOF

    # 添加内存使用信息
    mem_used_pct=$(awk '/MemTotal/{total=$2} /MemAvailable/{avail=$2} END{printf "%.1f", (total-avail)*100/total}' /proc/meminfo)
    echo "                    <div class=\"metric\"><span>内存使用率:</span><span>${mem_used_pct}%</span></div>" >> "$HTML_REPORT"

    cat >> "$HTML_REPORT" << EOF
                </div>
                <div class="info-card">
                    <h3>磁盘使用</h3>
                    <div>$(df -h / | tail -1 | awk '{print "根分区使用率: " $5}')</div>
                    <div class="metric"><span>最大磁盘使用率:</span><span>$(df -h | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{print $5}' | sed 's/%//' | sort -nr | head -1)%</span></div>
                </div>
                <div class="info-card">
                    <h3>网络状态</h3>
                    <div class="metric"><span>网络接口数:</span><span>$(ip link show | grep -c 'state UP')</span></div>
                    <div class="metric"><span>TCP连接数:</span><span>$(ss -t | grep -c ESTAB)</span></div>
                </div>
            </div>
        </div>

        <div class="section">
            <h2 class="section-title">🔍 详细巡检结果</h2>
            <div class="info-grid">
                <div class="info-card">
                    <h3>🔐 安全检查</h3>
                    <div class="metric"><span>SSH配置:</span><span>$(if [ -f /etc/ssh/sshd_config ]; then echo "已检查"; else echo "未配置"; fi)</span></div>
                    <div class="metric"><span>用户权限:</span><span>$(awk -F: '$3==0 {print $1}' /etc/passwd | wc -l) 个超级用户</span></div>
                    <div class="metric"><span>开放端口:</span><span>$(ss -tuln | grep LISTEN | wc -l) 个</span></div>
                </div>
                <div class="info-card">
                    <h3>⚙️ 系统配置</h3>
                    <div class="metric"><span>防火墙:</span><span>$(if systemctl is-active firewalld >/dev/null 2>&1; then echo "运行中"; elif iptables -L >/dev/null 2>&1; then echo "iptables活跃"; else echo "未启用"; fi)</span></div>
                    <div class="metric"><span>SELinux:</span><span>$(if command -v sestatus >/dev/null 2>&1; then sestatus | grep "SELinux status" | cut -d: -f2 | tr -d ' '; else echo "未安装"; fi)</span></div>
                    <div class="metric"><span>时间同步:</span><span>$(if systemctl is-active chronyd >/dev/null 2>&1 || systemctl is-active ntpd >/dev/null 2>&1; then echo "运行中"; else echo "未配置"; fi)</span></div>
                </div>
                <div class="info-card">
                    <h3>📊 服务状态</h3>
                    <div class="metric"><span>运行服务数:</span><span>$(systemctl list-units --type=service --state=running 2>/dev/null | grep -c 'running' || echo "无法获取")</span></div>
                    <div class="metric"><span>失败服务数:</span><span>$(systemctl --failed 2>/dev/null | grep -c 'loaded units' | awk '{if($1>0) print $1; else print "0"}')</span></div>
                    <div class="metric"><span>系统启动时间:</span><span>$(systemd-analyze 2>/dev/null | grep "Startup finished" | awk '{print $4}' || echo "无法获取")</span></div>
                </div>
            </div>
        </div>

        <div class="section">
            <h2 class="section-title">📋 系统健康总结</h2>
            <div class="info-grid">
                <div class="info-card">
                    <h3>🎯 巡检完成度</h3>
                    <div class="metric"><span>基础信息检查:</span><span class="status-ok">✅ 完成</span></div>
                    <div class="metric"><span>安全性检查:</span><span class="status-ok">✅ 完成</span></div>
                    <div class="metric"><span>性能分析:</span><span class="status-ok">✅ 完成</span></div>
                    <div class="metric"><span>配置合规:</span><span class="status-ok">✅ 完成</span></div>
                </div>
                <div class="info-card">
                    <h3>📈 趋势分析</h3>
                    <div class="metric"><span>系统运行时间:</span><span>$(uptime -p 2>/dev/null | sed 's/up //' || uptime | awk '{print $3 $4}')</span></div>
                    <div class="metric"><span>磁盘增长趋势:</span><span>$(df -h / | tail -1 | awk '{if($5+0 > 80) print "⚠️ 快速增长"; else if($5+0 > 60) print "🔄 中等增长"; else print "✅ 健康"}')</span></div>
                    <div class="metric"><span>建议巡检频率:</span><span>$(if [ "$(grep -c '\[CRITICAL\]' $LOG_FILE 2>/dev/null || echo 0)" -gt 0 ]; then echo "每日"; elif [ "$(grep -c '\[WARNING\]' $LOG_FILE 2>/dev/null || echo 0)" -gt 5 ]; then echo "每周"; else echo "每月"; fi)</span></div>
                </div>
            </div>
        </div>

        <div class="footer">
            <p>报告生成于 $(date) | Linux深度巡检工具 v$SCRIPT_VERSION</p>
            <p>详细日志请查看: $LOG_FILE</p>
            <p>💡 建议: 定期运行巡检确保系统安全稳定</p>
        </div>
    </div>
</body>
</html>
EOF

    echo -e "${GREEN}✅ HTML报告已生成: $HTML_REPORT${NC}"
    echo -e "${GREEN}✅ 详细日志保存在: $LOG_FILE${NC}"
    echo -e "${GREEN}✅ 报告目录: $REPORT_DIR${NC}"
}

# 完整的深度巡检
full_inspection() {
    print_section "开始完整深度巡检"
    
    init_report
    log_info "开始完整系统巡检"
    
    echo -e "${BLUE}=== 正在执行完整深度巡检，请稍候... ===${NC}\n"
    
    # 执行所有检查
    show_basic_info
    show_hardware_info
    show_disk_info
    show_network_info
    show_process_info
    show_security_info
    deep_security_check
    performance_monitoring
    compliance_check
    show_system_services
    show_logs
    
    # 生成报告
    generate_html_report
    
    print_section "巡检完成"
    log_info "系统巡检完成"
    
    # 显示汇总信息
    if [ -f "$LOG_FILE" ]; then
        warnings=$(grep "\[WARNING\]" "$LOG_FILE" | wc -l)
        criticals=$(grep "\[CRITICAL\]" "$LOG_FILE" | wc -l)
        
        echo -e "\n${BLUE}=== 巡检结果汇总 ===${NC}"
        echo -e "🚨 严重问题: ${RED}$criticals${NC}"
        echo -e "⚠️  警告问题: ${YELLOW}$warnings${NC}"
        echo -e "📊 详细报告: ${GREEN}$HTML_REPORT${NC}"
        echo -e "📋 原始日志: ${GREEN}$LOG_FILE${NC}"
        
        if [ "$criticals" -gt 0 ]; then
            echo -e "\n${RED}发现严重安全或性能问题，建议立即处理！${NC}"
        elif [ "$warnings" -gt 0 ]; then
            echo -e "\n${YELLOW}发现一些需要注意的问题，建议尽快处理。${NC}"
        else
            echo -e "\n${GREEN}系统状态良好，未发现重大问题。${NC}"
        fi
    fi
}

show_menu() {
    # 计算每列宽度 - 考虑中文字符占用双倍空间
    local col_width=28
    
    echo -e "\n${BLUE}=== Linux深度巡检工具箱 - 运维专业版 v$SCRIPT_VERSION ===${NC}"
    echo -e "${BLUE}┌──────────────────────────────┬──────────────────────────────┬──────────────────────────────┐${NC}"
    
    # 基础功能行
    printf "${BLUE}│${NC} %-28s ${BLUE}│${NC} %-28s ${BLUE}│${NC} %-28s ${BLUE}│${NC}\n" \
           "1) 系统基础信息               " \
           "2) 硬件信息                   " \
           "3) 磁盘使用情况               "
           
    echo -e "${BLUE}├──────────────────────────────┼──────────────────────────────┼──────────────────────────────┤${NC}"
    
    printf "${BLUE}│${NC} %-28s ${BLUE}│${NC} %-28s ${BLUE}│${NC} %-28s ${BLUE}│${NC}\n" \
           "4) 网络信息                   " \
           "5) 进程信息                   " \
           "6) 安全信息                   "
           
    echo -e "${BLUE}├──────────────────────────────┼──────────────────────────────┼──────────────────────────────┤${NC}"
    
    printf "${BLUE}│${NC} %-28s ${BLUE}│${NC} %-28s ${BLUE}│${NC} %-28s ${BLUE}│${NC}\n" \
           "7) 网络诊断                   " \
           "8) 系统服务状态               " \
           "9) 查看系统日志               "
           
    echo -e "${BLUE}├──────────────────────────────┼──────────────────────────────┼──────────────────────────────┤${NC}"
    
    # 高级功能行
    printf "${BLUE}│${NC} %-28s ${BLUE}│${NC} %-28s ${BLUE}│${NC} %-28s ${BLUE}│${NC}\n" \
           "🔍 10) 深度安全检查          " \
           "⚡ 11) 性能监控分析          " \
           "🔧 12) 配置合规检查          "
           
    echo -e "${BLUE}├──────────────────────────────┼──────────────────────────────┼──────────────────────────────┤${NC}"
    
    printf "${BLUE}│${NC} %-28s ${BLUE}│${NC} %-28s ${BLUE}│${NC} %-28s ${BLUE}│${NC}\n" \
           "🚀 13) 完整深度巡检          " \
           "📊 14) 生成HTML报告          " \
           "0) 退出                      "
           
    echo -e "${BLUE}└──────────────────────────────┴──────────────────────────────┴──────────────────────────────┘${NC}"
    echo -e "\n${YELLOW}💡 推荐使用 [13] 完整深度巡检 获得最全面的系统分析${NC}"
    echo -n "请输入选择 [0-14]: "
}

main() {
    print_header
    
    if [ $# -eq 0 ]; then
        while true; do
            show_menu
            read choice
            
            case $choice in
                1) show_basic_info ;;
                2) show_hardware_info ;;
                3) show_disk_info ;;
                4) show_network_info ;;
                5) show_process_info ;;
                6) show_security_info ;;
                7) network_diagnosis ;;
                8) show_system_services ;;
                9) show_logs ;;
                10) 
                    init_report
                    deep_security_check
                    ;;
                11) 
                    init_report
                    performance_monitoring
                    ;;
                12) 
                    init_report
                    compliance_check
                    ;;
                13) full_inspection ;;
                14) 
                    if [ -f "$LOG_FILE" ]; then
                        generate_html_report
                    else
                        echo -e "${YELLOW}请先运行巡检功能生成数据，然后再生成报告${NC}"
                    fi
                    ;;
                0) 
                    echo -e "${GREEN}再见!${NC}"
                    exit 0
                    ;;
                *) 
                    echo -e "${RED}无效选择，请重新输入${NC}"
                    ;;
            esac
            
            echo -e "\n${YELLOW}按Enter键继续...${NC}"
            read
        done
    else
        case $1 in
            "info") show_basic_info ;;
            "hardware") show_hardware_info ;;
            "disk") show_disk_info ;;
            "network") show_network_info ;;
            "process") show_process_info ;;
            "security") show_security_info ;;
            "deep-security") 
                init_report
                deep_security_check
                ;;
            "performance") 
                init_report
                performance_monitoring
                ;;
            "compliance") 
                init_report
                compliance_check
                ;;
            "full") full_inspection ;;
            "all") 
                show_basic_info
                show_hardware_info
                show_disk_info
                show_network_info
                show_process_info
                show_security_info
                ;;
            *) 
                echo "用法: $0 [选项]"
                echo ""
                echo "基础功能:"
                echo "  info          - 显示系统基础信息"
                echo "  hardware      - 显示硬件信息"
                echo "  disk          - 显示磁盘使用情况"
                echo "  network       - 显示网络信息"
                echo "  process       - 显示进程信息"
                echo "  security      - 显示安全信息"
                echo "  all           - 显示所有基础信息"
                echo ""
                echo "深度巡检功能:"
                echo "  deep-security - 深度安全检查"
                echo "  performance   - 性能监控分析"
                echo "  compliance    - 配置合规检查"
                echo "  full          - 完整深度巡检"
                echo ""
                echo "不带参数启动交互模式"
                ;;
        esac
    fi
}

main "$@"
